<template>
  <div class="bind-container">
    <h2>绑定账号</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label>手机号</label>
        <input
v-model="form.phone" type="tel" placeholder="请输入手机号" required />
      </div>

      <div class="form-group">
        <label>验证码</label>
        <div class="code-input">
          <input
v-model="form.code" type="text" placeholder="请输入验证码" required />
          <button type="button"
@click="sendCode" :disabled="codeSending">
            {{ codeSending ? `${countdown}s后重试` : '获取验证码' }}
          </button>
        </div>
      </div>

      <button type="submit"
:disabled="loading">
        {{ loading ? '绑定中...' : '立即绑定' }}
      </button>
    </form>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import { bindWechatAccount } from '@/services/wechat'

  const props = defineProps({
    wechatData: {
      type: Object,
      required: true,
    },
  })

  const form = ref({
    phone: '',
    code: '',
  })

  const loading = ref(false)
  const codeSending = ref(false)
  const countdown = ref(60)
  const error = ref('')

  const sendCode = async () => {
    if (!form.value.phone) {
      error.value = '请输入手机号'
      return
    }

    codeSending.value = true
    // TODO: 调用发送验证码接口
    console.log('发送验证码到:', form.value.phone)

    // 倒计时
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        codeSending.value = false
        countdown.value = 60
      }
    }, 1000)
  }

  const handleSubmit = async () => {
    try {
      loading.value = true
      error.value = ''

      // TODO: 验证表单数据
      if (!form.value.phone || !form.value.code) {
        error.value = '请填写完整信息'
        return
      }

      // 调用绑定接口
      const result = await bindWechatAccount(props.wechatData.openid, {
        phone: form.value.phone,
        code: form.value.code,
      })

      if (result.success) {
        // 绑定成功，跳转首页
        window.location.href = '/'
      } else {
        error.value = result.message || '绑定失败'
      }
    } catch (err) {
      error.value = '绑定过程出错，请重试'
      console.error('绑定错误:', err)
    } finally {
      loading.value = false
    }
  }
</script>

<style scoped>
  .bind-container {
    padding: 20px;
    max-width: 400px;
    margin: 0 auto;
  }

  .form-group {
    margin-bottom: 15px;
  }

  .code-input {
    display: flex;
    gap: 10px;
  }

  button[disabled] {
    opacity: 0.7;
  }
</style>
